package com.dffl.es.esstudy.controller;

import com.dffl.es.esstudy.document.EsSku;
import com.dffl.es.esstudy.feign.EsSearchFeignClient;
import com.dffl.es.esstudy.page.Page;
import com.dffl.es.esstudy.service.EsSkuService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * elasticsearch 搜索
 * @author liwensihan
 * @version 0.1
 * @date 2021/05/12 15:09
 */
@Api
@RestController
public class EsSearchController implements EsSearchFeignClient {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private EsSkuService esSearchService;

    /**
     * 新增 / 修改索引
     * @return
     */
    @Override
    public String add(@RequestBody EsSku sku) {
        esSearchService.save(sku);
        return "success";
    }

    /**
     * 删除索引
     * @return
     */
    @Override
    public String delete(@PathVariable Long id) {
        esSearchService.delete(id);
        return "success";
    }
    /**
     * 清空索引
     * @return
     */
    @Override
    public String deleteAll(@PathVariable String id) {
        esSearchService.deleteAll();
        return "success";
    }

    /**
     * 根据ID获取
     * @return
     */
    @Override
    public EsSku getById(@PathVariable Long id){
        return esSearchService.getById(id);
    }

    /**
     * 根据获取全部
     * @return
     */
    @Override
    public List<EsSku> getAll(){
        return esSearchService.getAll();
    }

    /**
     * 搜索
     * @param keyword
     * @return
     */
    @Override
    public List<EsSku> query(@PathVariable String keyword){
        return esSearchService.query(keyword,EsSku.class);
    }

    /**
     * 搜索，命中关键字高亮
     * @param keyword   关键字
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @Override
    public List<EsSku> queryHit(@RequestParam String keyword, @RequestParam String fields){

        return esSearchService.queryHit(keyword,EsSku.class,fields);
    }

    /**
     * 搜索，命中关键字高亮
     * @param pageNo    当前页
     * @param pageSize  每页显示的数据条数
     * @param keyword   关键字
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @Override
    public Page<EsSku> queryHitByPage(@RequestParam int pageNo, @RequestParam int pageSize
                                                    , @RequestParam String keyword, @RequestParam String fields){

        return esSearchService.queryHitByPage(pageNo,pageSize,keyword,EsSku.class,fields);
    }

    /**
     * 删除索引库
     * @param indexName
     * @return
     */
    @Override
    public String deleteIndex(@PathVariable String indexName){
        esSearchService.deleteIndex(indexName);
        return "success";
    }
}
